package com.cblz.bd.server.frontend.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cblz.bd.common.core.exception.BdAdminException;
import com.cblz.bd.common.core.utils.TreeUtil;
import com.cblz.bd.server.frontend.entity.BaUserRule;
import com.cblz.bd.server.frontend.entity.BaUserRuleTree;
import com.cblz.bd.server.frontend.mapper.BaUserRuleMapper;
import com.cblz.bd.server.frontend.service.BaUserGroupService;
import com.cblz.bd.server.frontend.service.BaUserRuleService;
import com.cblz.bd.server.frontend.service.BaUserService;
import io.vavr.control.Option;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author yanjieping
 * @description 针对表【ba_user_rule(会员权限规则表)】的数据库操作Service实现
 * @createDate 2022-11-04 15:09:54
 */
@Service("baUserRuleService")
@RequiredArgsConstructor
public class BaUserRuleServiceImpl extends ServiceImpl<BaUserRuleMapper, BaUserRule> implements BaUserRuleService {

    private final BaUserService baUserService;
    private final BaUserGroupService baUserGroupService;

    /**
     * 根据登录ID获取外部用户的访问权限
     *
     * @param loginId 登录ID
     * @return
     */
    @Override
    public List<BaUserRuleTree> getAllUserRule(Serializable loginId) {
        List<String> rulesList = baUserGroupService.getRulesByUserId(Option.of(baUserService.getById(loginId)).getOrElseThrow(() -> {
            throw new BdAdminException("未找到ID为「" + loginId + "」的用户");
        }).getGroupId())._2;

        if (rulesList.isEmpty())
            throw new BdAdminException("登录的账户没有任何权限,请联系网站管理员");

        List<BaUserRule> baUserRuleList;
        if (rulesList.contains("*")) {
            // 拿到所有菜单
            baUserRuleList = list(new LambdaQueryWrapper<BaUserRule>().ne(BaUserRule::getType, "route"));
        } else {
            // 拿到对应ID的菜单
            baUserRuleList = list(new LambdaQueryWrapper<BaUserRule>().in(BaUserRule::getId, rulesList));
        }

        List<BaUserRuleTree> trees = new ArrayList<>(Collections.emptyList());
        buildTrees(trees, baUserRuleList);

        List<BaUserRuleTree> resultTree = (List<BaUserRuleTree>) TreeUtil.build(trees);

        return resultTree;
    }

    private void buildTrees(List<BaUserRuleTree> trees, List<BaUserRule> rules) {
        rules.forEach(rule -> trees.add(BeanUtil.copyProperties(rule, BaUserRuleTree.class)));
    }
}




